package com.getpebble.android.main.sections.mypebble.view;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.framework.util.UiUtil;
import com.getpebble.android.common.framework.widget.AsyncImageView;
import com.getpebble.android.common.model.LoadedApp;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.common.model.PebbleColor;
import com.getpebble.android.jskit.bridge.JsAppLifecycleListener;
import com.getpebble.android.main.activity.MainActivity;
import com.getpebble.android.main.sections.appstore.fragment.NoConnectivityFragment;
import com.getpebble.android.main.sections.mypebble.fragment.LoadUnloadDialogFragment;
import com.getpebble.android.main.sections.mypebble.view.LoadedAppsCarousel.LoadedAppsAdapter;
import com.getpebble.android.util.HttpUtils;
import com.sun.mail.iap.Response;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.sql.Timestamp;
import java.util.Calendar;

public class LoadedWatchappsContainerView extends RelativeLayout implements OnPreDrawListener {
    public static final String TAG = LoadedWatchappsContainerView.class.getSimpleName();
    private AsyncImageView mCompanionAppIcon;
    private View mCompanionAppLayout;
    private LoadedAppsCarousel mLoadedAppsCarousel;
    private int mScreenWidth;
    private TextView mSlotUsage;
    private TextView mTxtSettings;
    private TextView mWatchAppTitle;
    private WatchFaceView mWatchImage;

    static /* synthetic */ class AnonymousClass5 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$common$model$PebbleColor = new int[PebbleColor.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$common$model$PebbleColor[PebbleColor.COLOR_BLACK.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$PebbleColor[PebbleColor.COLOR_WHITE.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$PebbleColor[PebbleColor.COLOR_RED.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$PebbleColor[PebbleColor.COLOR_ORANGE.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$PebbleColor[PebbleColor.COLOR_GRAY.ordinal()] = 5;
            } catch (NoSuchFieldError e5) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$PebbleColor[PebbleColor.COLOR_BIANCA_SILVER.ordinal()] = 6;
            } catch (NoSuchFieldError e6) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$PebbleColor[PebbleColor.COLOR_BIANCA_BLACK.ordinal()] = 7;
            } catch (NoSuchFieldError e7) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$PebbleColor[PebbleColor.COLOR_TINTIN_BLUE.ordinal()] = 8;
            } catch (NoSuchFieldError e8) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$PebbleColor[PebbleColor.COLOR_TINTIN_GREEN.ordinal()] = 9;
            } catch (NoSuchFieldError e9) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$PebbleColor[PebbleColor.COLOR_TINTIN_PINK.ordinal()] = 10;
            } catch (NoSuchFieldError e10) {
            }
        }
    }

    public LoadedWatchappsContainerView(Context context) {
        super(context);
        init();
    }

    public LoadedWatchappsContainerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LoadedWatchappsContainerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        View view = ((LayoutInflater) getContext().getSystemService("layout_inflater")).inflate(R.layout.view_loaded_watchapps_container, this, true);
        this.mWatchImage = (WatchFaceView) view.findViewById(R.id.watch_face_view);
        this.mTxtSettings = (TextView) view.findViewById(R.id.txt_settings);
        this.mWatchAppTitle = (TextView) view.findViewById(R.id.txt_watchapp_title);
        this.mSlotUsage = (TextView) view.findViewById(R.id.txt_slots_usage);
        this.mCompanionAppLayout = view.findViewById(R.id.companion_app_layout);
        this.mCompanionAppIcon = (AsyncImageView) view.findViewById(R.id.companion_app_icon);
        this.mLoadedAppsCarousel = (LoadedAppsCarousel) view.findViewById(R.id.loaded_apps_carousel);
        this.mLoadedAppsCarousel.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                final LoadedApp loadedApp = ((LoadedAppsAdapter) adapterView.getAdapter()).getLoadedApp(i);
                LoadedWatchappsContainerView.this.mWatchAppTitle.setText(loadedApp.getAppName().toUpperCase());
                if (loadedApp.getCompanionAppUrl() != null) {
                    LoadedWatchappsContainerView.this.mCompanionAppLayout.setVisibility(0);
                    LoadedWatchappsContainerView.this.mCompanionAppLayout.setOnClickListener(new OnClickListener() {
                        public void onClick(View view) {
                            Context context = LoadedWatchappsContainerView.this.getContext();
                            if (context != null) {
                                context.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(loadedApp.getCompanionAppUrl())));
                            }
                        }
                    });
                    if (loadedApp.getCompanionAppIcon() != null) {
                        LoadedWatchappsContainerView.this.mCompanionAppIcon.fetch(loadedApp.getCompanionAppIcon());
                    }
                } else {
                    LoadedWatchappsContainerView.this.mCompanionAppLayout.setVisibility(8);
                }
                if (loadedApp.isConfigurable()) {
                    LoadedWatchappsContainerView.this.mTxtSettings.setVisibility(0);
                } else {
                    LoadedWatchappsContainerView.this.mTxtSettings.setVisibility(4);
                }
            }

            public void onNothingSelected(AdapterView<?> adapterView) {
                LoadedWatchappsContainerView.this.mWatchAppTitle.setText("");
            }
        });
        this.mLoadedAppsCarousel.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                LoadUnloadDialogFragment dialogFragment = new LoadUnloadDialogFragment();
                LoadedApp loadedApp = ((LoadedAppsAdapter) adapterView.getAdapter()).getLoadedApp(i);
                dialogFragment.setWatchApp(loadedApp);
                FragmentManager fragmentManager = LoadedWatchappsContainerView.this.getFragmentManager();
                if (fragmentManager != null) {
                    dialogFragment.show(fragmentManager, loadedApp.getAppName());
                }
            }
        });
        this.mLoadedAppsCarousel.setDataSetObserver(new DataSetObserver() {
            public void onChanged() {
                LoadedAppsAdapter adapter = (LoadedAppsAdapter) LoadedWatchappsContainerView.this.mLoadedAppsCarousel.getAdapter();
                if (adapter == null || adapter.getCursor() == null) {
                    LoadedWatchappsContainerView.this.mTxtSettings.setVisibility(4);
                    LoadedWatchappsContainerView.this.mCompanionAppLayout.setVisibility(8);
                    return;
                }
                String slotUsageText;
                int count = adapter.getCount();
                if (count == 8) {
                    slotUsageText = LoadedWatchappsContainerView.this.getResources().getString(R.string.my_pebble_all_slots_used);
                } else {
                    slotUsageText = String.format(LoadedWatchappsContainerView.this.getResources().getString(R.string.my_pebble_slots_used), new Object[]{Integer.valueOf(count), Integer.valueOf(8)});
                }
                if (count == 0) {
                    LoadedWatchappsContainerView.this.mTxtSettings.setVisibility(4);
                    LoadedWatchappsContainerView.this.mCompanionAppLayout.setVisibility(8);
                }
                LoadedWatchappsContainerView.this.mSlotUsage.setText(slotUsageText);
                int recentlyAddedPosition = getRecentlyAddedAppPosition(adapter);
                if (recentlyAddedPosition != -1) {
                    LoadedWatchappsContainerView.this.mLoadedAppsCarousel.setSelection(recentlyAddedPosition);
                }
            }

            private int getRecentlyAddedAppPosition(LoadedAppsAdapter loadedAppsAdapter) {
                for (int i = 0; i < loadedAppsAdapter.getCount(); i++) {
                    LoadedApp loadedApp = loadedAppsAdapter.getLoadedApp(i);
                    if (loadedApp != null) {
                        Timestamp dateCreated = loadedApp.getInstalledCreatedDate();
                        Calendar c = Calendar.getInstance();
                        if (System.currentTimeMillis() - (dateCreated.getTime() + ((long) (c.get(15) + c.get(16)))) < 30000) {
                            Trace.debug(LoadedWatchappsContainerView.TAG, "Found recent app: " + loadedApp.getAppName());
                            return i;
                        }
                    }
                }
                return -1;
            }
        });
        this.mTxtSettings.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                LoadedApp loadedApp = ((LoadedAppsAdapter) LoadedWatchappsContainerView.this.mLoadedAppsCarousel.getAdapter()).getLoadedApp(LoadedWatchappsContainerView.this.mLoadedAppsCarousel.getSelectedItemPosition());
                MobileAppBehavior.logMyPebbleConfigSettingsTapped(loadedApp);
                Activity activity = (Activity) LoadedWatchappsContainerView.this.getContext();
                Trace.verbose(LoadedWatchappsContainerView.TAG, "Loaded WatchApp Settings: " + loadedApp.getUuid());
                Context context = LoadedWatchappsContainerView.this.getContext();
                if (context == null) {
                    Trace.error(LoadedWatchappsContainerView.TAG, "Loaded WatchApp Settings: Context was null");
                } else if (HttpUtils.hasInternetConnection(context)) {
                    JsAppLifecycleListener.onConfigLaunchRequest(LoadedWatchappsContainerView.this.getContext(), loadedApp.getUuid());
                } else if (activity != null) {
                    NoConnectivityFragment noConnectivityFragment = new NoConnectivityFragment();
                    noConnectivityFragment.configureRefreshToStartWebApp(context, loadedApp.getUuid());
                    ((MainActivity) activity).switchFragment(noConnectivityFragment, false, false, true);
                }
            }
        });
        this.mScreenWidth = UiUtil.getScreenWidth(getContext());
        getViewTreeObserver().addOnPreDrawListener(this);
    }

    public void setLoaderManager(LoaderManager loaderManager) {
        this.mLoadedAppsCarousel.setLoaderManager(loaderManager);
    }

    private FragmentManager getFragmentManager() {
        Context context = getContext();
        if (context == null || !(context instanceof Activity)) {
            return null;
        }
        return ((Activity) context).getFragmentManager();
    }

    public void onConnectedDeviceUpdated() {
        PblDeviceRecord connectedDeviceRecord = PebbleApplication.getConnectedDeviceRecord();
        if (connectedDeviceRecord == null) {
            this.mSlotUsage.setVisibility(4);
            setWatchBackgroundColor(PebbleColor.COLOR_UNKNOWN);
        } else {
            this.mSlotUsage.setVisibility(0);
            setWatchBackgroundColor(connectedDeviceRecord.color);
        }
        this.mLoadedAppsCarousel.onConnectedDeviceUpdated();
    }

    public void setWatchBackgroundColor(PebbleColor color) {
        this.mWatchImage.setImageDrawable(getMyPebbleDrawableForColor(color));
    }

    public void redraw() {
        Trace.debug(TAG, "redraw()");
        getViewTreeObserver().addOnPreDrawListener(this);
        invalidate();
    }

    public boolean onPreDraw() {
        if (getViewTreeObserver() != null && alignViews()) {
            getViewTreeObserver().removeOnPreDrawListener(this);
        }
        return true;
    }

    private boolean alignViews() {
        if (this.mWatchImage.getHeight() == 0) {
            return false;
        }
        int watchImageWidth = (int) (((float) this.mWatchImage.getHeight()) * 0.6535211f);
        this.mWatchImage.getLayoutParams().width = watchImageWidth;
        this.mTxtSettings.setWidth(watchImageWidth);
        if (this.mWatchAppTitle.getLayoutParams() != null) {
            this.mWatchAppTitle.getLayoutParams().width = (int) (((double) watchImageWidth) * 1.5d);
        }
        int watchAppItemHeight = (int) (((float) this.mWatchImage.getHeight()) / 2.1130953f);
        int watchAppItemWidth = (int) (((float) watchAppItemHeight) * 0.85714287f);
        MarginLayoutParams marginLayoutParams = (MarginLayoutParams) this.mLoadedAppsCarousel.getLayoutParams();
        int marginTop = ((getHeight() / 2) - (watchAppItemHeight / 2)) + getPixelsForDp(1);
        marginLayoutParams.setMargins(-(((this.mScreenWidth - (watchImageWidth - watchAppItemWidth)) - (getResources().getDimensionPixelOffset(R.dimen.my_pebble_watch_image_margin_left) * 2)) - watchAppItemWidth), marginTop, 0, 0);
        this.mLoadedAppsCarousel.setLayoutParams(marginLayoutParams);
        this.mLoadedAppsCarousel.setDimensions(watchAppItemWidth, watchAppItemHeight);
        return true;
    }

    private int getPixelsForDp(int dp) {
        DisplayMetrics metrics = new DisplayMetrics();
        ((WindowManager) getContext().getSystemService("window")).getDefaultDisplay().getMetrics(metrics);
        return (int) Math.ceil((double) (((float) dp) * metrics.density));
    }

    public boolean isPebbleFull() {
        LoadedAppsAdapter adapter = (LoadedAppsAdapter) this.mLoadedAppsCarousel.getAdapter();
        if (adapter != null && adapter.getCount() == 8) {
            return true;
        }
        return false;
    }

    private Drawable getMyPebbleDrawableForColor(PebbleColor color) {
        int drawableId;
        switch (AnonymousClass5.$SwitchMap$com$getpebble$android$common$model$PebbleColor[color.ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                drawableId = R.drawable.pebble_model_black;
                break;
            case SMTPMessage.RETURN_HDRS /*2*/:
                drawableId = R.drawable.pebble_model_white;
                break;
            case ListInfo.INDETERMINATE /*3*/:
                drawableId = R.drawable.pebble_model_red;
                break;
            case SMTPMessage.NOTIFY_DELAY /*4*/:
                drawableId = R.drawable.pebble_model_orange;
                break;
            case R.styleable.WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance /*5*/:
                drawableId = R.drawable.pebble_model_gray;
                break;
            case R.styleable.WalletFragmentStyle_maskedWalletDetailsBackground /*6*/:
                drawableId = R.drawable.pebble_model_steel_brushed;
                break;
            case R.styleable.WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance /*7*/:
                drawableId = R.drawable.pebble_model_steel_matte;
                break;
            case Response.NO /*8*/:
                drawableId = R.drawable.pebble_model_blue;
                break;
            case R.styleable.WalletFragmentStyle_maskedWalletDetailsLogoTextColor /*9*/:
                drawableId = R.drawable.pebble_model_green;
                break;
            case R.styleable.WalletFragmentStyle_maskedWalletDetailsLogoImageType /*10*/:
                drawableId = R.drawable.pebble_model_pink;
                break;
            default:
                drawableId = R.drawable.pebble_model_white;
                break;
        }
        return getResources().getDrawable(drawableId);
    }
}
